class Enter < ActiveRecord::Base
  
  include DynamicDefaultScoping
  
  validates :enterprise_id, :presence => true
  validates :order_item_id,
    :order_made_id,
    :presence => true
  validates :entered_count,
    :numericality => {
      :greater_than_or_equal_to => 1
    }

  belongs_to :order_item
  belongs_to :updated_by_user, :class_name => 'User', :foreign_key => :updated_by_user_id  
  belongs_to :feed
  belongs_to :order_made
  has_many :feeds, :dependent => :destroy, :order => 'position asc'

  default_scope :current_enterprise,lambda {where(:enterprise_id => Enterprise.current_id )}

  before_validation do |enter|
#    enter.enterprise_id ||= Enterprise.current_id
  end

  after_create do |enter|    
    Feed::EnterCreated.create!(
      :order_item_id => enter.order_item_id,
      :order_made_id => enter.order_made_id,
      :enter_id => enter.id)
  end

  before_save do |enter|
    enter.updated_by_user_id = User.current_id if enter.changed?
  end

  after_save do |enter|
    enter.order_item.order.update_attribute(:entered_on, enter.entered_on) if enter.order_item.order.entered_on.nil? or enter.order_item.order.entered_on < enter.entered_on
  end
  
  def reset_feed!
    update_attributes :feed_id => Feed.where(:enter_id => id).last.try(:id)
  end
end
